import sys
import pygame
from bullet import Bullet
from alien import Alien
from time import sleep


def check_events(ai_settings, scoreboard, screen, ship, stats, aliens, bullets, play_button):
    # 监视键盘和鼠标事件
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            update_high_score_file(stats)
            sys.exit()
        elif event.type == pygame.KEYDOWN:
            check_keydown_events(event, ai_settings, screen, ship, bullets)
        elif event.type == pygame.KEYUP:
            check_keyup_events(event, ship)
        elif event.type == pygame.MOUSEBUTTONDOWN:
            # 获取鼠标的位置
            mouse_x, mouse_y = pygame.mouse.get_pos()
            check_play_button(ai_settings, scoreboard, screen, ship,
                              stats, aliens, bullets, play_button, mouse_x, mouse_y)


def update_high_score_file(stats):
    if stats.high_score > stats.file_high_score:
        with open("high_score.txt", "w") as f_write:
            f_write.write(str(stats.high_score))


def reset_parameter(ai_settings, scoreboard, stats):
    # 实际上，点击play按钮，应该要重置游戏的信息
    stats.reset_stats()
    scoreboard.prep_images()
    # 重置动态参数
    ai_settings.initialize_dynamic_settings()


def check_play_button(ai_settings, scoreboard, screen, ship, stats, aliens, bullets, play_button, mouse_x, mouse_y):
    """如果玩家点击了鼠标，位置在play按钮范围内"""
    button_clicked = play_button.rect.collidepoint(mouse_x, mouse_y)
    # 通过这样的处理，只有当game_active为False时，点击按钮才会重置游戏
    if button_clicked and not stats.game_active:
        update_high_score_file(stats)
        reset_parameter(ai_settings, scoreboard, stats)
        reset_aliens_and_ship(ai_settings, screen, ship, aliens, bullets)
        stats.game_active = True
        # 游戏开始后，隐藏光标
        pygame.mouse.set_visible(False)


def update_screen(ai_settings, scoreboard, screen, ship, stats, aliens, bullets, play_button):
    """更新屏幕上的图像，并切换到新屏幕"""
    # 重绘屏幕
    screen.fill(ai_settings.bg_color)
    # 在飞船和外星人后面重绘所有子弹
    for bullet in bullets.sprites():
        bullet.draw_bullet()
    ship.blit_me()
    aliens.draw(screen)
    # 如果游戏处于非活动状态，则绘制button按钮
    if not stats.game_active:
        play_button.draw_button()
    scoreboard.draw_score()
    # 让绘制的屏幕可见
    pygame.display.flip()


def update_bullets(ai_settings, scoreboard, screen, ship, stats, aliens, bullets):
    """更新子弹的位置，并删除掉已被碰撞的子弹，以及外星人"""
    bullets.update()
    # 删除已消失的子弹
    for bullet in bullets.copy():
        if bullet.rect.bottom <= 0:
            bullets.remove(bullet)
    check_bullet_alien_collisions(ai_settings, scoreboard, screen, ship, stats, aliens, bullets)


def check_high_score(scoreboard, stats):
    # 检查是否产生了高分，如果产生了高分，则更新数据
    if stats.score > stats.high_score:
        stats.high_score = stats.score
        scoreboard.prep_high_score()


def start_new_level(ai_settings, scoreboard, screen, ship, stats, aliens, bullets):
    if len(aliens) == 0:
        # 加快游戏节奏
        ai_settings.increase_speed()
        stats.level += 1
        scoreboard.prep_level()
        # 删除现有的子弹，并新建一群外星人
        bullets.empty()
        create_fleet(ai_settings, screen, ship, aliens)


def check_bullet_alien_collisions(ai_settings, scoreboard, screen, ship, stats, aliens, bullets):
    # group collide是一个检查组碰撞的函数，第三个True对应第一个组，第四个True对应第二个组
    # True的意思是，删除掉已被碰撞的组对象
    collisions = pygame.sprite.groupcollide(bullets, aliens, True, True)
    if collisions:
        for hit_alien in collisions.values():
            stats.score += ai_settings.alien_points * len(hit_alien)
            scoreboard.prep_score()
    check_high_score(scoreboard, stats)
    start_new_level(ai_settings, scoreboard, screen, ship, stats, aliens, bullets)


def check_keydown_events(event, ai_settings, screen, ship, bullets):
    """响应按键"""
    if event.key == pygame.K_RIGHT:
        # 设置标志位
        ship.moving_right = True
    elif event.key == pygame.K_LEFT:
        ship.moving_left = True
    elif event.key == pygame.K_SPACE:
        fire_bullet(ai_settings, screen, ship, bullets)
    elif event.key == pygame.K_q:
        # 新增游戏退出的快捷键
        sys.exit()


def check_keyup_events(event, ship):
    """响应松开"""
    if event.key == pygame.K_RIGHT:
        # 修改标志位
        ship.moving_right = False
    elif event.key == pygame.K_LEFT:
        ship.moving_left = False


def fire_bullet(ai_settings, screen, ship, bullets):
    if len(bullets) < ai_settings.bullets_allowed:
        new_bullet = Bullet(ai_settings, screen, ship)
        bullets.add(new_bullet)


def create_fleet(ai_settings, screen, ship, aliens):
    """创建外星人群"""
    # 创建一个外星人，然后计算出一行能够容纳多少个外星人
    # 外星人的间距是外星人的宽度
    alien = Alien(ai_settings, screen)
    number_aliens_x = get_number_aliens_x(ai_settings, alien.rect.width)
    number_rows = get_number_rows(ai_settings, ship.rect.height, alien.rect.height)
    # 创建多行外星人，将他们加入到编组中
    for row_number in range(number_rows):
        for alien_number in range(number_aliens_x):
            create_alien(ai_settings, screen, aliens, alien_number, row_number)


def get_number_rows(ai_settings, ship_height, alien_height):
    available_space_y = (ai_settings.screen_height - 3 * alien_height - ship_height)
    number_rows = int(available_space_y / (2 * alien_height))
    return number_rows


def get_number_aliens_x(ai_settings, alien_width):
    """计算每行可以容纳多少个外星人"""
    available_space_x = ai_settings.screen_width - 2 * alien_width
    number_aliens_x = int(available_space_x / (2 * alien_width))
    return number_aliens_x


def create_alien(ai_settings, screen, aliens, alien_number, row_number):
    """创建一个外星人，并放在当前行的第alien_number位置"""
    alien = Alien(ai_settings, screen)
    alien_width = alien.rect.width
    alien.x = alien_width + 2 * alien_width * alien_number
    alien.rect.x = alien.x
    alien.rect.y = alien.rect.height + 2 * alien.rect.height * row_number
    aliens.add(alien)


def check_fleet_edges(ai_settings, aliens):
    """当有外星人到达边缘时，采取相应的措施"""
    for alien in aliens.sprites():
        if alien.check_edges():
            change_fleet_direction(ai_settings, aliens)
            break


def change_fleet_direction(ai_settings, aliens):
    """先将整群外星人下移，然后改变其运动方向"""
    for alien in aliens.sprites():
        alien.rect.y += ai_settings.fleet_drop_speed
    ai_settings.fleet_direction *= -1


def update_aliens(ai_settings, scoreboard, screen, ship, stats, aliens, bullets):
    """更新外星人的位置"""
    check_fleet_edges(ai_settings, aliens)
    aliens.update()
    # 检查外星人和飞船之间的碰撞
    if pygame.sprite.spritecollideany(ship, aliens):
        ship_hit(ai_settings, scoreboard, screen, ship, stats, aliens, bullets)
    # 检查外星人是否到达了底部
    check_aliens_bottom(ai_settings, scoreboard, screen, ship, stats, aliens, bullets)


def reset_aliens_and_ship(ai_settings, screen, ship, aliens, bullets):
    # 重新创建一批外星人
    aliens.empty()
    create_fleet(ai_settings, screen, ship, aliens)
    # 重新清空子弹
    bullets.empty()
    # 让飞船重新居中
    ship.center_ship()


def ship_hit(ai_settings, scoreboard, screen, ship, stats, aliens, bullets):
    # print("Ship hit!!!")
    # 将stats的ships_left减去1
    if stats.ships_left > 1:
        stats.ships_left -= 1
        # print(stats.ships_left)
        # 被撞击之后，应该也要更新scoreboard里面的飞船数量
        scoreboard.prep_ships()
        reset_aliens_and_ship(ai_settings, screen, ship, aliens, bullets)
        # 暂停0.5
        sleep(0.5)
    else:
        stats.game_active = False
        pygame.mouse.set_visible(True)


def check_aliens_bottom(ai_settings, scoreboard, screen, ship, stats, aliens, bullets):
    """如果外星人没有和飞船发生碰撞，但是确也到达了底部，那也需要重新开始"""
    screen_rect = screen.get_rect()
    for alien in aliens.sprites():
        if alien.rect.bottom >= screen_rect.bottom:
            # 像飞船被撞到一样处理
            ship_hit(ai_settings, scoreboard, screen, ship, stats, aliens, bullets)
            break
